package com.woniuxy.mqconsumer.mqlistener;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.woniuxy.mqconsumer.entity.Book;
import com.woniuxy.mqconsumer.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
@RabbitListener(queues = "order_dead_queue")
@Slf4j
public class OrderListenerConsumer {

    @Autowired
    OrderService orderService ;

    @RabbitHandler
    public void onMsg(Map<String, Object> msg, Channel channel, Message message) throws IOException {
        try {
           //取出 订单编号
            String orderNum = (String) msg.get("orderNum");
            //取出图书信息  [{"bookId":101,"buyCount":3},{"bookId":102,"buyCount":6}]
            String bookMsg = (String) msg.get("bookMsg");
            //把这个JSON数据转成 java对象
            ObjectMapper objectMapper = new ObjectMapper();
            List<Book> list = objectMapper.readValue(bookMsg, new TypeReference<List<Book>>() {});

            boolean b = orderService.cancelOrder(orderNum, list);
            log.info("取消订单成功:{}"+orderNum);
            //手动回应ack  1. 参数 1 ，获取当前消息的序号  参数 2 ，true  应答 比本消息序号小的 所有消息 false  应该本消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("消息消费失败 -->"+msg);
            /**
             * 拒绝确认消息:<br>
             * channel.basicNack(long deliveryTag, boolean multiple, boolean requeue) ; <br>
             * deliveryTag:该消息的index<br>
             * multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。<br>
             * requeue：被拒绝的是否重新入队列 <br>
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                    false, true);
        }
    }
}
